package _interface

import (
	"fmt"
	"gitee.com/leeqiang250/go-common/network"
	"gitee.com/leeqiang250/go-common/util"
	"net/http"
)

var chContext = make(chan *Context, 10240)
var https = make(map[string]Http)
var methods = make(map[string]map[string]bool)

func init() {
	go log()
}

func AddHttp(http Http) {
	https[http.Path()] = http
}

func Init() {
	var http__ Http
	for _, http__ = range https {
		if nil == http__ || nil == http__.Method() {
			continue
		}
		var method network.HttpMethod
		for _, method = range http__.Method() {
			if nil == methods[http__.Path()] {
				methods[http__.Path()] = make(map[string]bool)
			}
			methods[http__.Path()][string(method)] = true
		}
		http.HandleFunc(http__.Path(), func(response http.ResponseWriter, request *http.Request) {
			var context = Context{}
			context.StartTs = util.NowMs()
			context.Path = request.URL.Path
			var http_ = https[context.Path]
			if nil == http_ {
				return
			}
			http_.Start(request, response)
			if methods[context.Path][request.Method] {
				var dto = http_.GetDTO()
				var exist = nil == dto
				http_.SetDTO(request, dto)
				if http_.Verify(dto) {
					if exist {
						response.Write(util.Bytes(http_.Execute(request, response, dto)))
					} else {
						if nil == dto {
							response.Write(util.Bytes(http_.Error(request, response)))
						} else {
							response.Write(util.Bytes(http_.Execute(request, response, dto)))
						}
					}
				} else {
					response.Write(util.Bytes(http_.Error(request, response)))
				}
			} else {
				response.Write(util.Bytes(http_.Error(request, response)))
			}
			http_.End(request, response)
			context.EndTs = util.NowMs()
			chContext <- &context
		})
	}
}

func log() {
	var count uint64
	var context *Context
	for {
		context = <-chContext
		count++
		util.Request.Println(fmt.Sprintf("count:%v path:%v start:%v end:%v elapse:%v", count, context.Path, context.StartTs, context.EndTs, context.EndTs-context.StartTs))
	}
}
